package com.nhim.cms.admin.client;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;

public class ExtendedTree extends Tree {

	public ExtendedTree() {
		super();
	}

	@Override
	public void onBrowserEvent(Event event) {
		event.stopPropagation();
		event.preventDefault();
		switch (DOM.eventGetType(event)) {
		case Event.ONMOUSEDOWN:
			if (DOM.eventGetButton(event) == Event.BUTTON_RIGHT) {
				TreeItem item = findSelectedItem(null, event.getClientX(),
						event.getClientY());
				if (item != null && listener != null)
					listener.onRightClick(item, event);
			} else {
				super.onBrowserEvent(event);
			}
			break;
		case Event.ONCONTEXTMENU:
			break;
		default:
			super.onBrowserEvent(event);
			break;
		}
	}

	TreeItem findSelectedItem(TreeItem treeItem, int x, int y) {
		return findSelectedTreeItemRecursive(treeItem, x, y);
	}

	TreeItem findSelectedTreeItemRecursive(TreeItem treeItem, int x, int y) {
		if (null == treeItem) {
			int count = getItemCount();
			for (int i = 0; i < count; i++) {
				TreeItem selected = findSelectedTreeItemRecursive(getItem(i),
						x, y);
				if (selected != null) {
					return selected;
				}
			}
			return null;
		}
		int count = treeItem.getChildCount();
		for (int i = 0; i < count; i++) {
			TreeItem selected = findSelectedItem(treeItem.getChild(i), x, y);
			if (selected != null) {
				return selected;
			}
		}

		if (x >= treeItem.getAbsoluteLeft()
				&& x <= treeItem.getAbsoluteLeft() + treeItem.getOffsetWidth()
				&& y >= treeItem.getAbsoluteTop()
				&& y <= treeItem.getAbsoluteTop() + treeItem.getOffsetHeight()) {
			return treeItem;
		}
		return null;
	}

	private Listener listener;

	/**
	 * Custom listener for this widget.
	 */
	public interface Listener {

		/**
		 * Called when the user save Template
		 * 
		 */
		void onRightClick(TreeItem treeItem, Event event);
	}

	public void addRightClickListener(Listener listener) {
		this.listener = listener;
	}
}
